const {
  exec
} = require('../db/mysql')
const xss = require('xss')

// 获取博客列表
const getList = (page, limit) => {
  // offset 表示从第几页开始
  let offset = (page - 1) * limit;
  // console.log(page);
  // console.log(limit);
  // console.log(offset);
  let sql = ` SELECT * FROM blog order by createtime desc LIMIT ${offset}, ${limit};`

  // 返回 promise
  return exec(sql)
}
// 获取分页总数
const zhongshu = () => {
  // 这里的as kkk 代表把count(*) 变成了kkk 类似于赋值
  const sql = `select count(*) as kkk from  blog;`
  return exec(sql).then(rows => {
    return rows[0].kkk
  })
}

// 新建一篇博客
const newBlog = (blogData = {}) => {
  // blogData 是一个博客对象，包含 title content author 属性
  const title = xss(blogData.title)
  // console.log('title is', title)
  const content = xss(blogData.content)
  const img_tp = blogData.img_tp

  const createTime = Date.now()


  const sql = `
        insert into blog (title, content, createtime, img_tp)
        values ('${title}', '${content}', ${createTime}, '${img_tp}');
    `

  return exec(sql).then(insertData => {
    // console.log('insertData is ', insertData)
    return {
      id: insertData.insertId
    }
  })
}

// 更新一篇博客
const updateBlog = (blogData = {}) => {
  // id 就是要更新博客的 id
  // blogData 是一个博客对象，包含 title content 属性

  const title = xss(blogData.title)
  const content = xss(blogData.content)
  const id = blogData.id
  const img_tp = blogData.img_tp
  const createtime = Date.now()

  const sql = `
        update blog set title='${title}', content='${content}', createtime=${createtime},img_tp='${img_tp}' where id=${id}
    `

  return exec(sql).then(updateData => {
    // console.log('updateData is ', updateData)

    if (updateData.affectedRows > 0) {
      return true
    }
    return false
  })
}

const delBlog = (id) => {
  // id 就是要删除博客的 id
  const sql = `delete from blog where id='${id}' ;`
  return exec(sql).then(delData => {
    // console.log('delData is ', delData)
    if (delData.affectedRows > 0) {
      return true
    }
    return false
  })
}

module.exports = {
  getList,
  zhongshu,
  newBlog,
  updateBlog,
  delBlog,
  // tplog
}